<?php

(defined('BASEPATH')) OR exit('No direct script access allowed');

class Auth extends MX_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {

//        redirect('auth/login');
        $this->login();
    }

    public function is_logged_in() {

        if ($this->phpsession->get('is_logged_in'))
            return TRUE;

        return FALSE;
    }

    private $_last_message;

    /**
     *
     * @return view
     */
    public function login() {

//        if ($this->is_logged_in())
//            redirect('dashboard');
        if ($this->is_logged_in())
            redirect(base_url().'admin/tickets');

        $options = array();

        if ($this->is_postback())
            if (!$this->_do_login())
                $options['error'] = $this->_last_message;

        $this->load->view('auth/login', $options);
    }

    private function _do_login() {

        $this->form_validation->set_rules('email', __('email'), 'trim|required|valid_email|xss_clean');
        $this->form_validation->set_rules('password', __('password'), 'trim|required|xss_clean');
//        $this->form_validation->set_message('required', '%s ' . __('required_field'));
//        $this->form_validation->set_message('valid_email', '%s ' . __('valid_email_field'));
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        
        if (!$this->form_validation->run()) {

            $this->_last_message = validation_errors();
            return FALSE;
        } else {

            $options['email'] = trim($this->input->post('email'));
            $options['password'] = trim(md5($this->input->post('password')));
            $options['active'] = 1;

            $this->load->model('account/account_model');
            $users = $this->account_model->get_account($options);
//            print_r($users);die;
            if (count($users) == 1) {
                $this->phpsession->save('user_id', $users[0]->id);
                $this->phpsession->save('email', $users[0]->email);
                $this->phpsession->save('password', $users[0]->password);
                $this->phpsession->save('role', $users[0]->role);
                $this->phpsession->save('is_logged_in', TRUE);

                redirect(base_url().'admin/tickets');
//                redirect('dashboard');
            } else {
                $this->_last_message = '<div class="error">' . __('username_or_pw_incorrect_message') . '</div>';
                return FALSE;
            }
        }
    }

    /**
     * Destroy all session and lead end user to homepage
     */
    public function logout() {
        $this->phpsession->clear();
        redirect(base_url());
    }

}